# web.py

# Possibly interesting values:
#     CONTENT_LENGTH:
#     CONTENT_TYPE: application/x-www-form-urlencoded
#     PATH_INFO: /hello/mom/and/dad.html
#     QUERY_STRING: this=value&that=too
#     REMOTE_ADDR: 127.0.0.1
#     REQUEST_METHOD: GET
#     SCRIPT_NAME:
#     wsgi.errors: <file>
#     wsgi.file_wrapper: <file>
#     wsgi.input: <file to read request body>
#     wsgi.multiprocess: False
#     wsgi.multithread: True
#     wsgi.run_once: False

import webob
import wsgiref.util

Debug = 0

#Web_framework_dir = os.path.join(os.path.dirname(__file__), "media")
#
#Content_types = {
#    'html': 'text/html',
#    'js': 'text/javascript',
#    'css': 'text/css',
#    'gif': 'image/gif',
#    'png': 'image/png',
#    'jpeg': 'image/jpeg',
#    'jpg': 'image/jpeg',
#}

Module_cache = {}

def import_(modulename):
    ''' modulepath does not include .py
    '''
    if Debug: print >> sys.stderr, "import_:", modulename
    mod = __import__(modulename)
    for comp in modulename.split('.')[1:]:
        mod = getattr(mod, comp)
    return mod

def wsgi_app(environ, start_response):
    global Module_cache

    modulepath = wsgiref.util.shift_path_info(environ)
    assert modulepath, "Missing modulepath in URL"

    fn_name = wsgiref.util.shift_path_info(environ)
    assert fn_name, "Missing fn_name in URL"

    if modulepath not in Module_cache:
        Module_cache[modulepath] = import_('naimath.web.' + modulepath)

    fn = getattr(Module_cache[modulepath], fn_name)

    req = webob.Request(environ)

    return fn(req)(environ, start_response)
